package com.qf.shop.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.qf.shop.annotation.ProcessInfo;
import com.qf.shop.entity.Cart;
import com.qf.shop.entity.Goods;
import com.qf.shop.excel.listener.ExcelGoodsListener;
import com.qf.shop.model.Results;
import com.qf.shop.model.TableData;
import com.qf.shop.service.IGoodsService;
import com.qf.shop.vo.ExcelGoods;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import java.util.List;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/Goods")
public class GoodsController {

    private IGoodsService GoodsService;

    @Value("${imageServerSaveAddress}")
    private String fileLocation;

    public GoodsController(IGoodsService goodsServiceImpl) {
        GoodsService = goodsServiceImpl;
    }

    @GetMapping
    @ProcessInfo("查询全部商品数据")
    public TableData<Goods> getAllGoods(@RequestParam(defaultValue = "0") Integer offset,
                                        @RequestParam(defaultValue = "10") Integer limit){

        TableData<Goods> allGoods = GoodsService.getAllGoods(offset, limit);

        return allGoods;

    }
    @DeleteMapping("/{id}")
    @ProcessInfo("根据id删除商品")
    public Results deleteGoods(@PathVariable("id") Integer id){
        Results results = new Results();

        try{
            GoodsService.deleteGoodsById(id);
            results.setCode(1);
            results.setMsg("success");
        }catch (Exception e){
            e.printStackTrace();
            results.setCode(-1);
            results.setMsg("fail");
        }
            return results;
    }


    @PostMapping
    @ProcessInfo("添加商品")
    public Results addGoods(Goods goods){
        Results results = new Results();

        try{
            GoodsService.addGoods(goods);
            results.setCode(1);
            results.setMsg("success");
        }catch (Exception e){
            e.printStackTrace();
            results.setCode(-1);
            results.setMsg("fail");
        }

        return results;
    }

    // excel的导入
    @PostMapping("/import")
    public Results importExcel(MultipartFile userExcel) {
        Results results = new Results();
        try {
            EasyExcel.read(userExcel.getInputStream(), ExcelGoods.class, new ExcelGoodsListener(GoodsService)).sheet().doRead();
            results.setMsg("success");
            results.setCode(1);
        } catch (IOException ioException) {
            ioException.printStackTrace();
            results.setMsg("fail");
            results.setCode(-1);
        }
        return results;
    }



    // excel 的导出
    @GetMapping("/export")
    public Results export(HttpServletResponse response) {
        Results results = new Results();
        List<Goods> goodsList = GoodsService.getAllGoods();
        try {
            String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + ".xlsx";

            String fullPath = fileLocation + fileName; // excel文件的完整路径

            // 给List集合在初始化的时候, 指定长度, 是一个性能优化的点.
            List<ExcelGoods> excelGoods = new ArrayList<>(goodsList.size());

            for(Goods goods : goodsList) {
                System.out.println(goods.toString());
                ExcelGoods eu = new ExcelGoods();

                if (goods.getType().equals("1")){
                    eu.setItemId("手机");
                }else if (goods.getType().equals("2")){
                    eu.setItemId("电脑");
                }else if (goods.getType().equals("3")){
                    eu.setItemId("鞋子");
                }else if (goods.getType().equals("6")){
                    eu.setItemId("背包");
                }else if (goods.getType().equals("7")){
                    eu.setItemId("图书");
                }else if (goods.getType().equals("11")){
                    eu.setItemId("情趣");
                }else if (goods.getType().equals("12")){
                    eu.setItemId("汽车");
                }else if (goods.getType().equals("13")){
                    eu.setItemId("娃娃");
                }

                eu.setGoodsName(goods.getTitle());
                eu.setPrice(goods.getPrice());
                eu.setGoodsNumber(goods.getStock());

                System.out.println(eu.toString());
                excelGoods.add(eu);
            }
//
            goodsList = null;
            System.out.println(excelGoods);
            // 把 excel写入到临时目录
            EasyExcel.write(new File(fullPath), ExcelGoods.class).sheet("用户数据").doWrite(excelGoods);

            excelGoods = null;

            // 文件下载的头信息设置
            response.setHeader("content-disposition", "attachment;filename=" + fileName);

            // 写回文件
            IOUtils.copy(new FileInputStream(fullPath), response.getOutputStream());
            results.setCode(1);
            results.setMsg("success");
        } catch (Exception exception) {
            exception.printStackTrace();
            results.setMsg("fail");
            results.setCode(-1);
        }
        return results;
    }

    @GetMapping("cart/{id}")
    @ProcessInfo("根据id查看购物车")
    public List<Cart> showCart(@PathVariable("id")Integer id){
        List<Cart> cartList=GoodsService.showCart(id);
        return cartList;
    }

}
